package com.jianganming.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BioServer {

    public static void main(String[] args)throws Exception {
        ExecutorService threadPool = Executors.newCachedThreadPool();

        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动");
        while (true){
            final Socket socket = serverSocket.accept();
            threadPool.execute(()->{
                handler(socket);
            });
        }

    }

    private static void handler(Socket socket){
        byte[] bytes = new byte[1024];

        try {
            InputStream inputStream = socket.getInputStream();
            while (true){
                System.out.println("客户端连接进来，线程名："+Thread.currentThread().getName());
                int read = inputStream.read(bytes);
                System.out.println(new String(bytes,0,read));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
